using System;
using System.Collections.Generic;
using CGF;
using LitJson;
using UnityEngine;

/*
"id":373877408207474688,
"name":"user942932",
"email":"",
"phone":"",
"user_name":"wqb55",
"role":1,
"state":1,
"ip":"",
"icon":0,
"balance":0,
"wait_amount":0,
"reward":0,
"wallet":"",
"withdrawal_password":"",
"secret_key":"",
"what_app":"",
"level":0,
"parent_id":0,
"created_at":"2025-10-28T16:56:10.517+08:00",
"updated_at":"2025-10-28T16:56:10.517+08:00"
*/

public struct Event_UserInfoUpdate
{
}

public static class UserInfo
{
    public static bool HaveBoughtExpDevice
    {
        get { return PlayerPrefs.GetInt(UserId + "_HaveBoughtExpDevice") == 1; }
        set { PlayerPrefs.SetInt(UserId + "_HaveBoughtExpDevice", value ? 1 : 0); }
    }
    public static int total, balance, remain;

    public static async CTask<bool> IsLoggedIn()
    {
        //这里不使用Network封装类，因为无法判断登录状态
        Dictionary<string, string> header = string.IsNullOrEmpty(Token) ? null : new Dictionary<string, string>()
        {
            { "Authorization", $"Bearer {Token}" }
        };
        var res = await HttpHelper.PostJson(Config.Get.APIBaseUrl + "/v1/reward/oauth/check", null, header);
        if (res.success)
        {
            JsonData jsonData = JsonMapper.ToObject(res.text);
            if ((int)jsonData["code"] == 200)
            {
                Info = jsonData["data"]["user"];
                EventManager.Emit(new Event_UserInfoUpdate());
                return true;
            }
        }
        return false;
    }

    public static async CTask<bool> RefreshWallet()
    {
        //这里不使用Network封装类，因为无法判断登录状态
        Dictionary<string, string> header = string.IsNullOrEmpty(Token) ? null : new Dictionary<string, string>()
        {
            { "Authorization", $"Bearer {Token}" }
        };
        var res = await HttpHelper.Get(Config.Get.APIBaseUrl + "/v1/user/wallet", header);
        if (res.success)
        {
            JsonData jsonData = JsonMapper.ToObject(res.text);
            JsonData wallet = jsonData["data"]["wallet"];
            total = (int)wallet["balance"] + (int)wallet["income"] + (int)wallet["rewards"];
            balance = (int)wallet["balance"];
            remain = total - balance;
            EventManager.Emit(new Event_UserInfoUpdate());
            RefreshDiscount();
            return true;
        }
        return false;
    }

    public static string Account
    {
        get
        {
            string account = Info["email"].ToString();
            if (string.IsNullOrEmpty(account))
            {
                account = Info["phone"].ToString();
            }

            return account;
        }
    }

    public static string UserId
    {
        get { return Info["id"].ToString(); }
    }

    private static JsonData _userData;

    public static JsonData Info
    {
        get
        {
            if (_userData == null)
            {
                string str = PlayerPrefs.GetString("user_info");
                if (!string.IsNullOrEmpty(str))
                {
                    _userData = JsonMapper.ToObject(str);
                }
            }

            return _userData;
        }
        set
        {
            _userData = value;
            if (_userData != null)
            {
                if (string.IsNullOrEmpty(_userData["name"].ToString()))
                {
                    string name = PlayerPrefs.GetString("name");
                    if (string.IsNullOrEmpty(name))
                    {
                        name = $"Treinador{UnityEngine.Random.Range(1000, 10000)}";
                        PlayerPrefs.SetString("name", name);
                    }
                    _userData["name"] = name;
                }
                if (!string.IsNullOrEmpty(_userData["withdrawal_password"].ToString()))
                {
                    _userData["withdrawal_password"] = "******";
                }

                PlayerPrefs.SetString("user_info", JsonMapper.ToJson(_userData));
            }
            else
            {
                PlayerPrefs.DeleteKey("user_info");
            }
        }
    }

    public static float discount { get; private set; }

    public static bool IsUsernameLogin { get { return !string.IsNullOrEmpty(Info["user_name"].ToString()); } }

    private static async void RefreshDiscount()
    {
        var res = await Network.Get("/v1/config/cost");
        string level = Info["level"].ToString();
        discount = level == "0" ? 1 : MathHelper.Round((int)res.jsonData["data"][level]["duration"] * 0.01f, 2);
    }

    public static string Token
    {
        get { return PlayerPrefs.GetString("access_token"); }
        set { PlayerPrefs.SetString("access_token", value); }
    }

    public static void OnLogin(JsonData loginData)
    {
        Info = loginData["user"];
        Token = loginData["accessToken"].ToString();
        RefreshDiscount();
    }

    public static void OnLogout()
    {
        Token = null;
        Info = null;
        FirebaseHelper.SignOut();
    }
}
